package com.example.library_demo.controller;


import cn.hutool.crypto.SecureUtil;
import com.example.library_demo.common.Result;
import com.example.library_demo.dto.user.UserLoginDTO;
import com.example.library_demo.entity.User;
import com.example.library_demo.enums.GlobalResponseResultEnum;
import com.example.library_demo.service.IUserService;
import com.example.library_demo.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Eric
 * @since 2024-11-27
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody @Validated UserLoginDTO userLoginDTO) {
        String pass = SecureUtil.md5(userLoginDTO.getUsername() + userLoginDTO.getPassword());
        userLoginDTO.setPassword(pass);
        User user = userService.getUserByUsernameAndPassword(userLoginDTO);
        if (null == user) {
            return Result.error(GlobalResponseResultEnum.LOSE_AUTH_TOKEN_ERROR);
        }
        String token = SecureUtil.md5(user.getUsername() + LocalDateTime.now());
        user.setLoginDatetime(LocalDateTime.now());
        user.setToken(token);
        userService.updateById(user);

        UserInfoVO userInfoByUserId = userService.getUserInfoByUserId(user.getUserId());
        Map<String, Object> rst = new HashMap<>(2);
        rst.put("userInfo", userInfoByUserId);
        rst.put("token", token);
        return Result.success(rst);
    }

}

